package com.yonyou.pmclouds.enterprise.process;

import com.yonyou.pmclouds.basecom.bp.processor.SingleProcessor;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.runtime.RuntimeEnvironment;
import com.yonyou.pmclouds.enterprise.entity.EnterpriseQueryParam;
import com.yonyou.pmclouds.enterprise.entity.EnterpriseVO;
import com.yonyou.pmclouds.enterprise.mapper.EnterpriseMapper;
import com.yonyou.pmclouds.productactive.rmiitf.LicenseQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.MessageFormat;
import java.util.Date;

/**
 * @Author chulf
 * @Date 2020/4/15
 * @Description  授权数控制
 **/
@Component
public class AccountCehckBeforeProcess implements SingleProcessor<EnterpriseVO> {

    @Autowired
    private LicenseQuery licenseQuery;
    @Autowired
    private EnterpriseMapper mapper;

    @Override
    public void process(EnterpriseVO vo, EnterpriseVO orig) throws BusinessException {
        //先获得总的授权数
        int maxUserCountOfTenant = licenseQuery.getMaxUserCountOfTenant(RuntimeEnvironment.getTenantId(), new Date());

        //在获得已经授权数
        EnterpriseQueryParam param = new EnterpriseQueryParam();
        param.setTenantId(RuntimeEnvironment.getTenantId());
        EnterpriseVO[] enterpriseVOS = mapper.selectEtpsByCondition(param);

        int hasAuthorCount = 0;
        for (EnterpriseVO enterpriseVO : enterpriseVOS) {
            hasAuthorCount+=enterpriseVO.getPlanAuthorizedNum();
        }

        int ramainCount = maxUserCountOfTenant-hasAuthorCount; //剩余授权数量
        if (maxUserCountOfTenant < (hasAuthorCount+vo.getPlanAuthorizedNum())) {
            throw new BusinessException(MessageFormat.format("当前租户的余量为:{0}，最多只能授权为:{1};",ramainCount,ramainCount));
        }
    }
}
